﻿using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using Avalonia;
using Avalonia.Collections;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Platform.Storage;
using FluentAvalonia.UI.Controls;
using iOSClub.Toolkit.WindowApp.Controls;
using iOSClub.Toolkit.WindowApp.Pages;
using iOSClub.Toolkit.WindowApp.ViewModels.Pages;
using Newtonsoft.Json;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using Toolkit.Lib.iOSModels;

namespace iOSClub.Toolkit.WindowApp.MemberControls;

public partial class ClubManageControl : UserControl
{
    private List<SignModel> List { get; set; } = new();

    public ClubManageControl()
    {
        InitializeComponent();
    }

    protected override async void OnAttachedToVisualTree(VisualTreeAttachmentEventArgs e)
    {
        base.OnAttachedToVisualTree(e);
        var model = ViewServes.GetViewData<iOSManagerPageModel>(this);
        if (model == null) return;
        List = await model.GetAllData() ?? new List<SignModel>();
        DataGrid.ItemsSource = new DataGridCollectionView(List);
        ChooseBox.ItemsSource = SignRecord.ChooseType;
        ChooseBox.SelectedItem = SignRecord.ChooseType[0];
    }

    private async void DownloadClick(object? sender, RoutedEventArgs e)
    {
        var top = TopLevel.GetTopLevel(this);
        if (top == null) return;

        var result = await top.StorageProvider.SaveFilePickerAsync(new FilePickerSaveOptions()
        {
            DefaultExtension = ".xlsx",
            Title = "将数据保存到"
        });

        if (result == null) return;

        var table =
            (DataTable)JsonConvert.DeserializeObject(JsonConvert.SerializeObject(DataGrid.ItemsSource),
                typeof(DataTable))!;

        await using var fs = await result.OpenWriteAsync();
        IWorkbook workbook = new XSSFWorkbook();
        var excelSheet = workbook.CreateSheet("Sheet1");

        var columns = new List<string>();
        var row = excelSheet.CreateRow(0);
        var columnIndex = 0;

        foreach (DataColumn column in table.Columns)
        {
            columns.Add(column.ColumnName);
            row.CreateCell(columnIndex).SetCellValue(column.ColumnName);
            columnIndex++;
        }

        var rowIndex = 1;
        foreach (DataRow destroy in table.Rows)
        {
            row = excelSheet.CreateRow(rowIndex);
            var cellIndex = 0;
            foreach (var col in columns)
            {
                row.CreateCell(cellIndex).SetCellValue(destroy[col].ToString());
                cellIndex++;
            }

            rowIndex++;
        }

        workbook.Write(fs);
        workbook.Dispose();
    }

    private async void UpdateClick(object? sender, RoutedEventArgs e)
    {
        if (sender is not Control control) return;
        if (control.DataContext is not SignModel signModel) return;
        var model = ViewServes.GetViewData<iOSManagerPageModel>(this);
        if (model == null) return;

        var iosModel = iOSMemberModel.AutoCopy<SignModel, iOSMemberModel>(signModel);
        iosModel.Identity = await model.GetMemberIdentity(signModel.ToLogin());
        
        var td = new TaskDialog
        {
            Title = "西建大iOS Club工具包",
            Header = "社团成员管理",
            Content = new UpdateMemberDataControl(iosModel),
            IconSource = new SymbolIconSource { Symbol = Symbol.People },
            FooterVisibility = TaskDialogFooterVisibility.Never,
            XamlRoot = (Visual)VisualRoot!,
            Buttons =
            {
                TaskDialogButton.OKButton,
                TaskDialogButton.CancelButton
            }
        };
        
        var fail = new TaskDialog
        {
            Title = "西建大iOS Club工具包",
            Header = "社团成员管理",
            Content = "出现了问题!",
            IconSource = new SymbolIconSource { Symbol = Symbol.People },
            FooterVisibility = TaskDialogFooterVisibility.Never,
            XamlRoot = (Visual)VisualRoot!,
            Buttons =
            {
                TaskDialogButton.OKButton
            }
        };
        
        td.Closing += async (dialog, args) =>
        {
            if ((TaskDialogStandardResult)args.Result != TaskDialogStandardResult.OK) return;
            if (td.Content is not UpdateMemberDataControl content) return;
            var result = content.Done();
            if (result?.model == null) return;
            if (result.Value.permission != null)
                await model.UpdateIdentity(result.Value.permission);
            if (!await model.Update(result.Value.model!, true)) 
                await fail.ShowAsync();
        };
        await td.ShowAsync(true);
    }

    private async void DeleteClick(object? sender, RoutedEventArgs e)
    {
        if (sender is not Control control) return;
        if (control.DataContext is not SignModel signModel) return;
        var td = new TaskDialog
        {
            Title = "西建大iOS Club工具包",
            Header = "社团成员管理",
            Content = "是否要删除这个成员?",
            IconSource = new SymbolIconSource { Symbol = Symbol.People },
            FooterVisibility = TaskDialogFooterVisibility.Never,
            XamlRoot = (Visual)VisualRoot!,
            Buttons =
            {
                TaskDialogButton.OKButton,
                TaskDialogButton.CancelButton
            }
        };
        td.Closing += async (dialog, args) =>
        {
            if ((TaskDialogStandardResult)args.Result != TaskDialogStandardResult.OK) return;
            var model = ViewServes.GetViewData<iOSManagerPageModel>(this);
            if (model == null) return;
            var r = await model.Delete(signModel.UserId);
            if (!r)
            {
                var a = new ContentDialog()
                {
                    Title = "西建大iOS Club工具包",
                    Content = "删除失败",
                    PrimaryButtonText = "Ok"
                };
                await a.ShowAsync();
                return;
            }
            List = await model.GetAllData() ?? new List<SignModel>();
            DataGrid.ItemsSource = new DataGridCollectionView(List);
        };
        await td.ShowAsync(true);
    }

    private void SearchSelectionChanged(object? sender, SelectionChangedEventArgs e)
    {
        if (sender is not FAComboBox comboBox) return;
        var s = comboBox.SelectedItem as string;
        if (string.IsNullOrEmpty(s)) return;
        switch (s)
        {
            case "学院":
                SearchComboBox.IsVisible = true;
                SearchComboBox.ItemsSource = SignRecord.Academies;
                SearchBox.IsVisible = false;
                break;
            case "政治面貌":
                SearchComboBox.IsVisible = true;
                SearchComboBox.ItemsSource = SignRecord.PoliticalLandscapes;
                SearchBox.IsVisible = false;
                break;
            case "性别":
                SearchComboBox.IsVisible = true;
                SearchComboBox.ItemsSource = SignRecord.Genders;
                SearchBox.IsVisible = false;
                break;
            default:
                SearchBox.IsVisible = true;
                SearchComboBox.IsVisible = false;
                break;
        }
    }

    private void SearchBoxKeyDown(object? sender, KeyEventArgs e)
    {
        if (e.Key != Key.Enter) return;
        if (string.IsNullOrEmpty(SearchBox.Text)) return;
        var c = ChooseBox.SelectedItem as string;
        if (string.IsNullOrEmpty(c)) return;
        DataGrid.ItemsSource = c switch
        {
            "姓名" => List.Where(x => x.UserName.StartsWith(SearchBox.Text)),
            "学号" => List.Where(x => x.UserId.StartsWith(SearchBox.Text)),
            "班级" => List.Where(x => x.ClassName.StartsWith(SearchBox.Text)),
            "手机号码" => List.Where(x => x.PhoneNum.StartsWith(SearchBox.Text)),
            _ => DataGrid.ItemsSource
        };
    }

    private void SearchComboBoxChanged(object? sender, SelectionChangedEventArgs e)
    {
        var s = SearchComboBox.SelectedItem as string;
        if (string.IsNullOrEmpty(s)) return;
        var c = ChooseBox.SelectedItem as string;
        if (string.IsNullOrEmpty(c)) return;
        DataGrid.ItemsSource = c switch
        {
            "学院" => List.Where(x => x.Academy == s),
            "政治面貌" => List.Where(x => x.PoliticalLandscape == s),
            "性别" => List.Where(x => x.Gender == s),
            _ => DataGrid.ItemsSource
        };
    }

    private async void UploadClick(object? sender, RoutedEventArgs e)
    {
        var top = TopLevel.GetTopLevel(this);
        if (top == null) return;

        var result = await top.StorageProvider.OpenFilePickerAsync(new FilePickerOpenOptions(){Title = "选定Json数据文件"});
        if(result.Count == 0)return;

        var model = ViewServes.GetViewData<iOSManagerPageModel>(this);
        if (model == null) return;
        
        using var reader = new StreamReader(await result[0].OpenReadAsync());
        
        await model.AddJsonData(await reader.ReadToEndAsync());
    }
}